package com.bwie.handler;

import com.bwie.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * @author 郜怀达
 * @version 1.0
 * @description: 统一异常处理类
 * @date 2022/9/14 23:16
 */

@RestControllerAdvice//全局异常  访问控制器异常进行捕获
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义业务异常(需手动抛出)
     */
    @ExceptionHandler(CreateMyException.class)
    public CreateResult<?> setException(CreateMyException e) {
        log.error("业务异常: {}", e.getMessage(), e);
        return CreateResult.fail(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常（自动触发）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CreateResult<?> handleValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        String errorMsg = result.getFieldErrors().stream()
                .map(fieldError -> fieldError.getField()  + ": " + fieldError.getDefaultMessage())
                .collect(Collectors.joining(";  "));
        return CreateResult.fail(ErrorCode.PARAM_ERROR.getCode(),  errorMsg);
    }

    /**
     * 处理所有未被捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public CreateResult<?> handleGlobalException(Exception e) {
        log.error(" 系统异常: {}", e.getMessage(),  e);
        return CreateResult.fail(ErrorCode.SYSTEM_ERROR.getCode(),  "系统繁忙，请稍后再试");
    }
}
